import { html } from 'lit';
import { ifDefined } from 'lit/directives/if-defined.js';
import { styleMap } from 'lit/directives/style-map.js';
import { Meta, Canvas, ArgsTable, Story } from '@storybook/addon-docs';
import { userEvent } from '@storybook/testing-library';

<Meta
  title="Components/Radio/Radio Group"
  component="bl-radio-group"
  argTypes={{
    label: {
      control: 'text',
      type: 'string'
    },
    name: {
      control: 'text',
      type: 'string'
    },
    value: {
      control: 'text',
      type: 'string'
    },
    required: {
      control: 'boolean',
    },
  }}
/>

export const RadioGroupTemplate = (args) => html`
<bl-radio-group
    class='${ifDefined(args.class)}'
    label='${ifDefined(args.label)}'
    name='${ifDefined(args.name)}'
    value='${ifDefined(args.value)}'
    ?required=${args.required}
    >${args.options.map((option) =>
      html`\n  <bl-radio value=${option.value}>${option.label}</bl-radio>`
    )}
</bl-radio-group>`

export const StyledTemplate = (args) => html`
<style>
  .${args.class} {
    --bl-radio-direction: row;
  }
</style>
${RadioGroupTemplate(args)}
`

export const AlignmentRadioGroupTemplate = (args) => html`
<bl-radio-group
    class='${ifDefined(args.class)}'
    label='${ifDefined(args.label)}'
    name='${ifDefined(args.name)}'
    value='${ifDefined(args.value)}'
    ?required=${args.required}
    >${args.options.map((option) =>
      html`\n  <bl-radio value=${option.value} class='${ifDefined(args.radioClass)}'>${option.label}</bl-radio>`
    )}
</bl-radio-group>`

export const AlignmentsTemplate = (args) => html`
<style>
  .${args.class} {
    --bl-radio-direction: row;
    --bl-radio-group-cross-axis-item-alignment: center;
    --bl-radio-group-main-axis-content-alignment: center;
  }
  .${args.radioClass} {
    width: 200px;
  }
</style>
${AlignmentRadioGroupTemplate(args)}
`

export const KeyboardNavigationTemplate = (args) => html`
<input id="previnput" placeholder="Previous Input" autofocus>
${RadioGroupTemplate(args)}
`

export const focusSecondOption = async ({ }) => {
  await userEvent.keyboard('[Tab]');
  await userEvent.keyboard('[ArrowRight]');
}

# Radio Group Component

<bl-badge icon="document">[ADR](https://github.com/Trendyol/baklava/issues/135)</bl-badge>
<bl-badge icon="puzzle">[Figma](https://www.figma.com/file/RrcLH0mWpIUy4vwuTlDeKN/Baklava-Design-Guide?node-id=1510%3A6857)</bl-badge>
<bl-badge icon="check_fill">RTL Supported</bl-badge>

Radio Group component is a form field component to take a selection from user with a list of options. It needs to be used with `bl-radio` component.

<Canvas>
  <Story name="Basic Usage" args={{ label: 'Payment Type', name: 'paymentType', options: [{ value: 'cc', label: 'Credit Card'}, {value: 'ideal', label: 'iDeal'}] }}>
    {RadioGroupTemplate.bind({})}
  </Story>
</Canvas>

If you set a `value`, the option with that value will be selected.

<Canvas>
  <Story name="Value set" args={{ label: 'Payment Type', name: 'paymentType', value: 'ideal', options: [{ value: 'cc', label: 'Credit Card'}, {value: 'ideal', label: 'iDeal'}] }}>
    {RadioGroupTemplate.bind({})}
  </Story>
</Canvas>

Radio Group component handles keyboard navigation and highlights active radio option while navigating with keyboard. First `Tab` focuses on first available option and user can navigate with arrow keys within options, and `Space` key for selecting it.

<Canvas>
  <Story name="Focused option" args={{ label: 'Payment Type', name: 'paymentType', value: 'cc', options: [{ value: 'cc', label: 'Credit Card'}, {value: 'ideal', label: 'iDeal'}] }} play={focusSecondOption}>
    {KeyboardNavigationTemplate.bind({})}
  </Story>
</Canvas>

By default radio options are listed in vertical stack. You can change this by setting `--bl-radio-direction` CSS variable as `row`.

<Canvas>
  <Story name="Horizontal Stack" args={{ label: 'Payment Type', name: 'paymentType', value: 'ideal', class: 'payment-type-field', options: [{ value: 'cc', label: 'Credit Card'}, {value: 'ideal', label: 'iDeal'}] }}>
    {StyledTemplate.bind({})}
  </Story>
</Canvas>

By default radio options acts as default flex layout. You can change this by setting `--bl-radio-group-cross-axis-item-alignment`, `--bl-radio-group-cross-axis-content-alignment` and `--bl-radio-group-main-axis-content-alignment` CSS variables.

<Canvas>
  <Story name="Aligning radio elements" args={{ label: 'Alignments', name: 'paymentType', value: 'ideal', class: 'alignment-field', radioClass:'alignment-item', options: [{ value: 'loremone', label: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cum amet aperiam provident mollitia.'}, {value: 'loremtwo', label: 'Lorem, ipsum dolor.'}] }}>
    {AlignmentsTemplate.bind({})}
  </Story>
</Canvas>

## RTL Support

The radio group component supports RTL (Right-to-Left) text direction. You can enable RTL mode by setting the `dir` attribute on a parent element or the `html` tag.

<Canvas>
  <Story name="RTL Support">
    {() => html`
      <div style="display: flex; gap: 16px;">
        <div>
          <p style="margin-bottom: 8px;">LTR (Left-to-Right)</p>
          <bl-radio-group label="Select Payment Method" name="payment">
            <bl-radio value="credit">Credit Card</bl-radio>
            <bl-radio value="debit">Debit Card</bl-radio>
            <bl-radio value="cash">Cash</bl-radio>
          </bl-radio-group>
        </div>
        <div dir="rtl">
          <p style="margin-bottom: 8px;">RTL (Right-to-Left)</p>
          <bl-radio-group label="اختر طريقة الدفع" name="payment">
            <bl-radio value="credit">بطاقة ائتمان</bl-radio>
            <bl-radio value="debit">بطاقة خصم</bl-radio>
            <bl-radio value="cash">نقدي</bl-radio>
          </bl-radio-group>
        </div>
      </div>
    `}
  </Story>
</Canvas>

Here's a vanilla JavaScript and HTML example of how to use RTL support:

```html
<!-- index.html -->
<html>
<head>
  <meta charset="UTF-8">
  <title>Baklava Radio Group RTL Example</title>
  <!-- Import Baklava's CSS and JavaScript -->
  <script type="module" src="path/to/baklava.js"></script>
  <style>
    .container {
      margin: 20px;
    }
    .flex-container {
      display: flex;
      gap: 20px;
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <div class="container">
    <button onclick="toggleDirection()">Toggle RTL/LTR</button>

    <div class="flex-container">
      <!-- LTR Example -->
      <div>
        <h3>LTR Radio Group</h3>
        <bl-radio-group label="Select Payment Method" name="payment">
          <bl-radio value="credit">Credit Card</bl-radio>
          <bl-radio value="debit">Debit Card</bl-radio>
          <bl-radio value="cash">Cash</bl-radio>
        </bl-radio-group>
      </div>

      <!-- RTL Example -->
      <div dir="rtl">
        <h3>RTL Radio Group</h3>
        <bl-radio-group label="اختر طريقة الدفع" name="payment">
          <bl-radio value="credit">بطاقة ائتمان</bl-radio>
          <bl-radio value="debit">بطاقة خصم</bl-radio>
          <bl-radio value="cash">نقدي</bl-radio>
        </bl-radio-group>
      </div>
    </div>
  </div>

  <script>
    // Example of dynamically changing direction
    const toggleDirection = () => {
      const rtlContainer = document.querySelector('[dir="rtl"]');
      rtlContainer.dir = rtlContainer.dir === 'rtl' ? 'ltr' : 'rtl';
    };

    // Example of creating a radio group programmatically
    const createRadioGroup = (isRTL) => {
      const container = document.createElement('div');
      if (isRTL) container.dir = 'rtl';

      const radioGroup = document.createElement('bl-radio-group');
      radioGroup.label = isRTL ? 'اختر طريقة الدفع' : 'Select Payment Method';
      radioGroup.name = 'payment';

      const options = isRTL
        ? [['credit', 'بطاقة ائتمان'], ['debit', 'بطاقة خصم'], ['cash', 'نقدي']]
        : [['credit', 'Credit Card'], ['debit', 'Debit Card'], ['cash', 'Cash']];

      options.forEach(([value, label]) => {
        const radio = document.createElement('bl-radio');
        radio.value = value;
        radio.textContent = label;
        radioGroup.appendChild(radio);
      });

      container.appendChild(radioGroup);
      document.body.appendChild(container);
    };
  </script>
</body>
</html>
```


## Reference

<ArgsTable of="bl-radio-group" />
